<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import grapesjs from "grapesjs";
import "grapesjs/dist/css/grapes.min.css";
import gjsPresetWebpage from "grapesjs-preset-webpage";
import gjsBlocksBasic from "grapesjs-blocks-basic";
import gjsPluginForms from "grapesjs-plugin-forms";
import gjsPluginFlexbox from "grapesjs-blocks-flexbox";
import gjsPluginClick from "grapesjs-click";
import gjsPluginCkeditor from "grapesjs-plugin-ckeditor";
import gjsPluginCustomCode from "grapesjs-custom-code";
import zh from "grapesjs/locale/zh";
import { processHtmlTemplate } from "@/utils/templateUtils";
import { registerTemplateType } from "@/utils/templateUtils";
const editor = ref<any>(null);
// 栏目id和栏目条数
const newsConfigs = ref<Record<string, { limit: string; topid: string }>>({});

// 新闻类型枚举

// 公共方法：获取新闻模块配置
const getNewsConfig = (component: any) => {
  const type = component.getAttributes()["data-news-type"];
  if (!newsConfigs.value[component.cid]) {
    newsConfigs.value[component.cid] = {
      limit: "0,7",
      topid: "4295",
    };
  }
  return {
    ...newsConfigs.value[component.cid],
    type,
  };
};

// 公共方法：更新新闻模块配置
const updateNewsConfig = (
  component: any,
  config: { limit?: string; topid?: string }
) => {
  const cid = component.cid;
  newsConfigs.value[cid] = {
    ...newsConfigs.value[cid],
    ...config,
  };
  component.setAttributes({
    "data-limit": config.limit || newsConfigs.value[cid].limit,
    "data-topid": config.topid || newsConfigs.value[cid].topid,
  });
};

onMounted(() => {
  editor.value = grapesjs.init({
    container: "#gjs",
    fromElement: true,
    height: "calc(100vh - 0px)",
    width: "100vw",
    autorender: true,
    forceClass: false,

    cssIcons:
      "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css",
    style: ".gjs-cv-canvas { top: 0; width: 100%; height: 100%; }",

    // 面板配置
    panels: {
      defaults: [
        {
          id: "layers",
          el: ".panel__right",
          resizable: {
            maxDim: 350,
            minDim: 200,
            tc: true, // Top handler
            cl: true, // Left handler
            cr: true, // Right handler
            bc: true, // Bottom handler
          },
        },
      ],
    },
    plugins: [
      gjsPresetWebpage,
      gjsBlocksBasic,
      gjsPluginFlexbox,
      gjsPluginClick,
      gjsPluginCustomCode,
      // gjsPluginCkeditor,
      // gjsPluginForms,
    ],
    // storageManager: {
    //   type: null, // 禁用本地存储
    //   autosave: false, // 禁用自动保存
    //   autoload: false, // 禁用自动加载
    // },
    i18n: {
      messages: { zh },
    },
    canvas: {
      scripts: ["/js/jquery.min.js", "/js/swiper-bundle.min.js"],
      styles: ["/css/swiper-bundle.min.css", "/css/normalize.css"],
    },

    // 基础配置
  });

  editor.value.on("load", () => {
    // 1. 确保组件类型定义完整
    editor.value.DomComponents.addType("news-component", {
      isComponent: (el) => el.getAttribute?.("data-czkj") === "news",
      model: {
        defaults: {
          traits: [
            {
              type: "text",
              name: "data-limit",
              label: "显示条数",
              placeholder: "例如: 0,7",
              changeProp: true,
              default: "0,7", // 设置默认值
            },
            {
              type: "text",
              name: "data-topid",
              label: "栏目ID",
              placeholder: "例如: 4295",
              changeProp: true,
              default: "4295", // 设置默认值
            },
          ],
          attributes: {
            // 添加默认属性
            "data-czkj": "news",
            "data-limit": "0,7",
            "data-topid": "4295",
          },
        },
        init() {
          // 监听两个属性的变化
          this.on("change:data-limit change:data-topid", () => {
            this.setAttributes({
              "data-czkj": "news",
              "data-limit": this.get("data-limit"),
              "data-topid": this.get("data-topid"),
            });
          });

          // 初始化时设置属性
          this.setAttributes({
            "data-czkj": "news",
            "data-limit": this.get("data-limit"),
            "data-topid": this.get("data-topid"),
          });
          // // 监听limit变化
          // this.on("change:data-limit", () => {
          //   const limit = this.get("data-limit");
          //   this.setAttributes({ "data-limit": limit });
          //   console.log("limit updated:", limit);
          // });

          // // 监听topid变化
          // this.on("change:data-topid", () => {
          //   const topid = this.get("data-topid");
          //   this.setAttributes({ "data-topid": topid });
          //   console.log("topid updated:", topid);
          // });
        },
      },
    });
    // 2. 修改区块定义，确保组件类型正确应用

    editor.value.BlockManager.add("my-custom-news1", {
      label: "新闻1",
      category: "新闻",
      content: {
        components: `
        <style>
        .w8auto {
            width: 100%;
            position: relative;
            margin: auto;
            margin-top: 30px;
        }

        .tzgg {
            /* display: inline-block; */
            width: 80%;
            margin: auto;
            position: relative;
            vertical-align: top;
        }

        .tzgg-item {
            margin-top: 30px;
        }

        .tzgg-item>a {
            display: block;
            padding: 10px 0;
            border-bottom: 1px solid #efefef;
        }

        .tzgg-item>a:last-child {
            border: none;
        }

        .tzgg-item>a>.time {
            display: inline-block;
            width: 84px;
            height: 79px;
            background-image: url(../images/pc/tzgg-time-bg.png);
            background-size: 100% 100%;
            margin-right: 22px;
            vertical-align: text-top;
            text-align: center;
            padding-top: 8px;
        }

        .tzgg-item>a>.time>strong {
            font-size: 24px;
            color: #FEFEFE;
            font-weight: 400;
            font-family: "Georgia";
        }

        .tzgg-item>a>.time>span {
            font-weight: 400;
            font-size: 16px;
            color: #2341B8;
            display: block;
            margin-top: 16px;
            font-family: "Georgia";
        }

        .tzgg-item>a>.text {
            display: inline-block;
            width: calc(100% - 160px);
            vertical-align: text-top;
        }

        .tzgg-item>a>.text h2 {
            font-weight: 400;
            font-size: 19px;
            color: #2C2C2C;
            margin-bottom: 21px;
        }

        .tzgg-item>a>.text p {
            font-size: 14px;
            color: #9F9F9F;
        }

        .about {
            position: absolute;
            right: 0;
            top: 40px;
            transition: all .3s;
        }

        .about:hover {
            position: absolute;
            right: 0;
            top: 40px;
            transform: rotate(360deg);
        }

        .one-slh {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    </style>
    <div class="w8auto m-auto" data-czkj="news">
        <div class="tzgg">
            <img src="/images/pc/tzgg.png" class=" wow animate__animated animate__fadeInUp" alt="" srcset="">
            <a href="#" class="about">
                <img src="/images/pc/about.png" alt="" srcset="">
            </a>
            <div class="tzgg-item  wow animate__animated animate__fadeInUp" data-czkj-news="list" >
                <a href="#" data-czkj-news-url>
                    <div class="time">
                        <strong data-czkj-news-time-day>05</strong>
                        <span data-czkj-news-time-year-month>2024.06</span>
                    </div>
                    <div class="text">
                        <h2 class="one-slh" data-czkj-news-title> 2024年公开招聘员额制辅导员公告</h2>
                        <p class="one-slh" data-czkj-news-title>河南省教育厅、河南省体育局主办的河南省第十九届学生武术比赛局主办十九......</p>
                    </div>
                </a>
                <a href="#">
                    <div class="time">
                        <strong>07</strong>
                        <span>2024.06</span>
                    </div>
                    <div class="text">
                        <h2 class="one-slh"> 关于开展2024年度河南省教育科学研究成果评定工作的通知</h2>
                        <p class="one-slh">各学院、各部门：现将2024年度河南省教育科学研究成果评定工作有关事宜通知如下：......</p>
                    </div>
                </a>
                <a href="#">
                    <div class="time">
                        <strong>30</strong>
                        <span>2024.05</span>
                    </div>
                    <div class="text">
                        <h2 class="one-slh"> 关于做好2024年度河南省政府决策研究招标课题立项申报工作的通知</h2>
                        <p class="one-slh">各学院、各部门：经河南省政府决策研究课题招标领导小组研究决定，2024年度河南......</p>
                    </div>
                </a>
                <a href="#">
                    <div class="time">
                        <strong>28</strong>
                        <span>2024.05</span>
                    </div>
                    <div class="text">
                        <h2 class="one-slh"> 关于做好2024年度全国教育科学规划专项课题申报工作的通知</h2>
                        <p class="one-slh">2024年度，全国教育科学规划新增“高校毕业生就业研究专项”（以下简称就业研究专项）......</p>
                    </div>
                </a>
            </div>
        </div>
    </div>
        `,
      },
      traits: ["data-limit", "data-topid"],
    });

    editor.value.BlockManager.add("my-custom-news2", {
      label: "新闻2",
      category: "新闻",
      content: {
        components: `
         <style>
        .w8auto {
            width: 100%;
            position: relative;
            margin: auto;
            margin-top: 30px;
        }

        .jcdt {
            width: 80%;
            /* display: inline-block; */
            margin: auto;
            position: relative;
            vertical-align: top;
        }

        .jcdt-item {
            vertical-align: top;
            margin-top: 30px;
        }

        .jcdt-item>a:hover {
            color: #1267BB;
        }

        .jcdt-item>a {
            display: inline-block;
            width: 100%;
            font-size: 18px;
            color: #24272C;
            /* vertical-align: middle; */
            padding: 16px 0;
            border-bottom: 1px solid #efefef;
        }

        .jcdt-item>a:nth-child(1) {
            border-bottom: none;
        }

        .jcdt-item>a:nth-child(2) {
            border-top: none;
            margin-top: 10px;
        }

        .jcdt-item>a:last-child {
            /* border: none; */
        }

        .jcdt-item>a::before {
            content: '';
            width: 5px;
            height: 5px;
            display: inline-block;
            background: #536ECE;
            border-radius: 50%;
            margin-right: 10px;
            margin-bottom: 4px;
        }

        .ji_1 a {
            display: flex;
            color: #333;
        }

        .ji_2 a {
            display: block;
            line-height: 55px;
            color: #333;
        }


        .one-slh {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }

        .about {
            position: absolute;
            right: 0;
            top: 40px;
            transition: all .3s;
        }

        .about:hover {
            position: absolute;
            right: 0;
            top: 40px;
            transform: rotate(360deg);
        }
    </style>
    <div class="w8auto m-auto" data-czkj="news">
        <div class="jcdt">
            <img src="/images/pc/jcdt.png" class=" wow animate__animated animate__fadeInUp" alt="" srcset="">
            <a href="#" class="about">
                <img src="/images/pc/about.png" alt="" srcset="">
            </a>
            <div class="jcdt-item  wow animate__animated animate__fadeInUp">
                <div class="ji_1" data-czkj-news="list" data-limit="0,1" data-topid="4295">
                    <a href="#" class="first-item" data-czkj-news-url>
                        <span class="first-left">
                            <img class="imgScaleTranStition imgScale" width="400px" style="margin-right: 20px;"
                                src="/images/pc/1.jpg" alt="" data-czkj-news-img >
                        </span>
                        <div>
                            <p class="two-slh" data-czkj-news-title>我校召开第五次学生代表大会</p>
                            <span><img src="/images/pc/rl.png" /> <strong data-czkj-news-time-year-month>2024年06月17日</strong></span>
                        </div>
                    </a>
                </div>
                <div class="ji_2" data-czkj-news="list" data-limit="1,5" data-topid="4295">
                    <a href="#" class="one-slh" data-czkj-news-url>
                        <span data-czkj-news-title>粽趣飘香，多彩端午|我校开展“我们的节日·端午” 主题团日活动</span>
                    </a>
                    <a href="#" class="one-slh">浓情端午 暖心送粽——后勤处为师生发放暖心粽子 </a>
                    <a href="#" class="one-slh">粽趣飘香·祈福端午主题团日活动 </a>
                    <a href="#" class="one-slh">应用技术学院召开学生安全工作会议</a>
                </div>

            </div>
        </div>
    </div>
        `,
      },
      traits: ["data-limit", "data-topid"],
    });

    editor.value.BlockManager.add("my-custom-news3", {
      label: "底部",
      category: "新闻",
      content: {
        components: `
       <footer style="width: 100%; line-height: 43px;    height: 43px;background: #2951A2; margin-top: 27px;">
     <div style="text-align: center; color: #fff;">河南省郑州市金水区平安大道197号 邮政编码：450003 电话：0371-55633660 <a href="" style="color: #fff;"
            target="_blank">豫ICP备2022006548号-1</a></div>
</footer>
        `,
      },
    });

    editor.value.BlockManager.add("my-custom-nav", {
      label: "导航",
      category: "导航",
      content: {
        components: `
         <style>
        .w100 {
            width: 100%;
        }

        .header-box {
            background: #2F46BC;
            height: 131px;
            padding: 0px 0 20px;
            z-index: 100;
        }

        .nav-bar {
            height: 33px;
            background-color: #2D3F90;
        }

        .nav-bar>div {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #A8C6EC;
            font-size: 12px;
            line-height: 33px;
        }

        .nav-bar>div span {
            margin-left: 20px;
        }

        .nav-bar>div i {
            margin: 0px 5px 0px 0;
            vertical-align: top;
        }


        .nav2-wrapper {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .w1647 {
            width: 100%;
        }

        .nav2-wrapper>a>img {
            height: 70px;
            margin: 13px 0 0;
        }

        .nav2>ul {
            margin-top: 25px !important;
        }

        .nav2 ul>li:nth-child(5) {
            margin-right: 60px !important;
        }

        .nav2-wrapper {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .nav2-wrapper>a>img {
            height: 70px;
            margin: 13px 0 0;
        }

        .nav2>ul {
            margin-top: 25px !important;
        }


        /* #nav {
    float: right;
} */
        .nav-bar {
            height: 33px;
            background-color: #2D3F90;

        }

        .nav-bar>div {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #A8C6EC;
            font-size: 12px;
            line-height: 33px;
        }

        .nav-bar>div span {
            margin-left: 20px;
        }

        .nav-bar>div i {
            margin: 0px 5px 0px 0;
            vertical-align: top;
        }

        .center-logo {
            position: absolute;
            top: -65px;
            left: 50%;
            transform: translateX(-50%);
        }

        #nav>ul {
            display: flex;
            padding: 0;
            width: 100%;
            /* justify-content: space-between; */
            margin-top: 41px;
        }

        #nav>ul>li {
            position: relative;
            z-index: 9999999999999;
            margin: -10px 60px 0 0;
            display: flex;
            align-items: center;
        }

        #nav>ul>li:nth-child(5) {
            margin-right: 590px;
        }

        #nav>ul>li span {
            display: inline-block;
            width: .3125rem;
            height: .3125rem;
            background: #b2b2b2;
            border-radius: 50%;
        }

        #nav>ul>li>a {
            display: block;
            padding: 0;
            text-transform: uppercase;
        }

        #nav>ul>li>a {
            font-weight: bolder;
            font-size: 1rem;
            color: #fff;
            line-height: 40px;
            position: relative;
            transition: .6s;
            display: flex;
            align-items: center;
            border-top: none;
            border-bottom: none;
        }

        #nav>ul>li.on>a {
            font-weight: bold;
        }

        #nav>ul>li>a .h3 {
            position: relative;
            font-size: 1rem;
            padding: 0;
            z-index: 1;
        }

        #nav>ul>li a i {
            display: inline-block;
            width: 9px;
            height: 6px;
            background-size: contain;
            vertical-align: middle;
            margin-left: 8px;
        }

        #nav>ul>li .sub {
            position: absolute;
            position: absolute;
            left: 50%;
            top: 100%;
            z-index: 9999999999999;
            /* -webkit-box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.2); */
            -moz-box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.2);
            /* box-shadow: 0px 3px 5px #3333334d; */
            transform-origin: 0 0 0;
            transform: scaleY(0.2) translateX(-50%);
            -webkit-transition: all 0.3s ease 0s;
            -moz-transition: all 0.3s ease 0s;
            transition: all 0.3s ease 0s;
            opacity: 0;
            padding: 20px 0 0;
            min-width: 100%;
        }

        #nav>ul>li .sub:before {
            content: "";
            position: absolute;
            border-left: transparent 6px solid;
            border-right: transparent 6px solid;
            border-bottom: #fff 8px solid;
            top: 13px;
            left: 50%;
            margin-left: -6px;
            box-shadow: 0 3px 15px rgba(0, 0, 0, .05);
        }

        #nav>ul>li .sub .box {
            padding: 0;
            text-align: center;
            border-radius: 0;
            overflow: hidden;
            background: rgba(255, 255, 255, .85);
            box-shadow: 0 3px 30px rgba(0, 0, 0, .08);
        }

        #nav>ul>li .sub a {
            padding: 0 1.5rem;
            line-height: 3.5;
            transition: .3s;
            font-size: 14px;
            letter-spacing: 1px;
            color: #636363;
            /* border-bottom: 1px dashed #eee; */
            display: block;
            white-space: nowrap;
            position: relative
        }

        #nav>ul>li .sub a:before {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            width: 3px;
            height: 0;
            background: #537a78;
            transition: .5s;
        }

        #nav>ul>li .sub a:hover {
            color: #fff;
            background: #3E54C0;
        }

        #nav>ul>li .sub a:hover:before {
            height: 100%;
        }

        #nav>ul>li:hover .sub {
            filter: alpha(opacity=100);
            -moz-opacity: 1;
            -khtml-opacity: 1;
            opacity: 1;
            visibility: visible;
            transform: translateY(0px) translateX(-50%);
        }

        #nav>ul>li.on>a,
        #nav>ul>li:hover>a,
        #header.xg #nav>ul>li.on>a,
        #header.xg #nav>ul>li:hover>a {
            color: #fff;
        }

        #nav>ul>li .h3:after {
            content: "";
            display: block;
            width: 100%;
            height: 7px;
            position: absolute;
            left: 50%;
            margin-left: -50%;
            top: -3.5px;
            transition: .5s;
            border-radius: 3.5px;
            z-index: -1;
            display: none;
        }

        #nav>ul>li h3:before {
            content: "";
            display: block;
            position: absolute;
            left: 50%;
            margin-left: -3px;
            border-left: transparent 3px solid;
            border-right: transparent 3px solid;
            border-bottom: #3E54C0 4px solid;
            bottom: 2px;
            transition: .3s;
            opacity: 0;
            visibility: hidden;
            display: none;
        }

        #nav>ul>li:hover h3:after,
        #nav>ul>li.on h3:after {
            transform: translateY(0);
        }

        #nav>ul>li:hover h3:before,
        #nav>ul>li.on h3:before {
            opacity: 1;
            visibility: visible
        }
    </style>
    <header class="w100 header-box header-box2" style="color: #fff;">
        <div class="nav-bar w100">
            <div class="w1647 m-auto">
                <div>欢迎访问，驻马店幼儿师范高等专科学校！</div>
                <div>
                    <span><i class="iconfont icon-shouye"></i>设为首页</span>
                    <span><i class="iconfont icon-wangluo"></i>English</span>
                </div>
            </div>
        </div>
        <div class="w80 m-auto clearfix w1647 nav2-wrapper">
            <a href="#">
                <img src="/images/pc/logo2.png" alt="" srcset="">
            </a>
            <nav id="nav" class="nav2" data-czkj="nav">
                <ul data-czkj-nav="list">
                    <li>
                        <a href="#" data-czkj-nav-url title="">
                            <div class="h3" data-czkj-nav-name>学校概况</div>
                        </a>
                        <div class="sub">
                            <div class="box" data-czkj-nav-child>
                                <a href="#" title="" data-czkj-nav-sed-url >
                                <span data-czkj-nav-sed-name>学校概况</span>
                                </a>
                                <a href="#" title="现任领导">现任领导</a>
                                <a href="#" title="形象标识">形象标识</a>
                                <a href="#" title="校园生活">校园生活</a>
                            </div>
                        </div>
                    </li>
                    <li>
                        <a href="#" title="机构设置">
                            <div class="h3">机构设置</div>
                        </a>

                    </li>
                    <li>
                        <a href="#" title="学院设置">
                            <div class="h3">学院设置</div>
                        </a>
                    </li>
                    <li>
                        <a href="#" title="教学科研">
                            <div class="h3">教学科研</div>
                        </a>
                    </li>
                    <li>
                        <a href="#" title="招生就业">
                            <div class="h3">招生就业</div>
                        </a>
                    </li>
                    <li>
                        <a href="#" title="人才招聘">
                            <div class="h3">人才招聘</div>
                        </a>
                    </li>
                    <li>
                        <a href="#" title="图书馆">
                            <div class="h3">图书馆</div>
                        </a>
                    </li>
                    <li>
                        <a href="#" title="校务公开">
                            <div class="h3">校务公开</div>
                        </a>
                    </li>
                    <i class="iconfont icon-sousuo" onclick="$('.blank').show()"
                        style="color: #fff;font-size: 25px;margin-top: -4px;"></i>
                </ul>
            </nav>
        </div>
    </header>
        `,
      },
    });
  });

  editor.value.DomComponents.addType("swiper-container", {
    model: {
      defaults: {
        script: function () {
          // 这段代码会在组件渲染到画布后执行
          if (window.Swiper) {
            new Swiper(this.querySelector(".zmd-swiper"), {
              autoplay: 3000,
              paginationClickable: true,
              loop: true,
              pagination: ".swiper-pagination",
            });
          }
        },
        components: `<style>
        .zmd-swiper{
            width: 100vw;
            height: 400px;
        }
        .zmd-swiper .swiper-slide img {
         width: 100%;
         height: 100%;
         object-fit: cover;
       }
    </style>
    <div class="zmd-swiper swiper-container" data-czkj="banner">
      <div class="swiper-wrapper" data-czkj-banner="list">
        <div class="swiper-slide">
          <a href="#" data-czkj-banner-url>
            <img  src="/images/pc/1.jpg" data-czkj-banner-img/>
          </a>
        </div>
        <div class="swiper-slide">
          <a href="#" >
            <img src="/images/pc/2.jpg"/>
          </a>
        </div>
        <div class="swiper-slide">
          <a href="#">
            <img  src="/images/pc/1.jpg" />
          </a>
        </div>
        <div class="swiper-slide">
          <a href="#">
            <img src="/images/pc/2.jpg"/>
          </a>
        </div>
      </div>
      <div class="swiper-pagination"></div>
    </div>`,
        traits: [
          {
            name: "autoplay",
            type: "number",
            label: "自动播放(ms)",
            default: 3000,
          },
          { name: "loop", type: "checkbox", label: "循环播放", default: true },
        ],
      },
    },
    view: {
      onRender({ el }) {
        // 确保Swiper库已加载
        if (!window.Swiper) {
          console.warn("Swiper库未加载");
          return;
        }

        // 延迟初始化确保DOM就绪
        setTimeout(() => {
          this.swiper = new Swiper(el.querySelector(".zmd-swiper"), {
            autoplay: this.model.get("autoplay"),
            loop: this.model.get("loop"),
            pagination: {
              el: ".swiper-pagination",
              clickable: true,
            },
          });
        }, 100);
      },

      onRemove() {
        // 组件移除时销毁Swiper实例
        if (this.swiper) {
          this.swiper.destroy();
        }
      },
    },
  });

  editor.value.BlockManager.add("swiper", {
    label: "Swiper轮播",
    category: "高级组件",
    content: { type: "swiper-container" },
    media: `<svg viewBox="0 0 24 24"><path d="M4,4H20A2,2 0 0,1 22,6V18A2,2 0 0,1 20,20H4A2,2 0 0,1 2,18V6A2,2 0 0,1 4,4M4,6V18H20V6H4M8,8H16V16H8V8Z"/></svg>`,
  });

  // 添加自定义样式
  editor.value.on("load", async () => {
    // 先清除所有样式
    // editor.value.CssComposer.getAll().reset();
    const testCss = `
        .header-box {
          background: red !important; /* 测试用醒目颜色 */
        }
      `;
    // editor.value.CssComposer.addRules(testCss)
    // editor.value.render();
  });

  editor.value.on("component:selected", (component) => {
    if (component.getAttributes()["data-czkj"] === "news") {
      const limit = component.get("data-limit");
      const topid = component.get("data-topid");
      console.log("当前选中的新闻组件:", {
        cid: component.cid,
        limit,
        topid,
      });
    }
  });

  // 生成模板
  editor.value.on("load", () => {
    editor.value.DomComponents.getWrapper().onAll((component) => {
      component.view.el.__grapesjs_editor = editor.value;
    });
    // 添加生成按钮到工具栏
    editor.value.Panels.addButton("options", {
      id: "generate-template",
      className: "fa fa-file-code-o",
      command: "generate-template",
      attributes: { title: "生成模板" },
      active: false,
    });
    // 添加生成命令
    editor.value.Commands.add("generate-template", {
      run: (editor) => {
        const html = editor.getHtml();
        console.log("html:", html);
        const css = editor.getCss();
        const processed = processHtmlTemplate(html);

        // 获取配置的CSS和JS资源
        const styles = editor.getConfig().canvas.styles || [];
        const scripts = editor.getConfig().canvas.scripts || [];

        // 生成CSS链接
        const styleLinks = styles
          .map((style) => `<link rel="stylesheet" href="${style}">`)
          .join("\n    ");

        // 生成JS脚本
        const scriptTags = scripts
          .map((script) => `<script src="${script}"><\/script>`)
          .join("\n    ");

        const fullHtml = `
          <!DOCTYPE html>
          <html>
          <head>
            <meta charset="UTF-8">
            <title>Generated Template</title>
             ${styleLinks}
             ${scriptTags}
            <style>${css}</style>
          </head>
          <body>
            ${processed}
          </body>
          </html>
              `;
        console.log(fullHtml);
      },
    });
  });
});

// 添加组件卸载时的清理逻辑
onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.destroy();
  }
});
</script>

<template>
  <div class="card">
    <div id="gjs"></div>
  </div>
</template>

<style>
.gjs-block svg {
  width: 50%;
}
</style>
